package com.ldk.api;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.config.AlipayConfig;
import com.alipay.util.AlipayNotify;
import com.ldk.base.framework.util.ConvertUtil;
import com.ldk.framework.entity.Alipay;
import com.ldk.framework.entity.Tenpay;
import com.ldk.framework.entity.Unionpay;
import com.ldk.framework.enums.TripNoType;
import com.ldk.framework.service.IAlipayService;
import com.ldk.framework.service.IRechargeOrderService;
import com.ldk.framework.service.IServiceTripService;
import com.ldk.framework.service.ITenpayService;
import com.thoughtworks.xstream.XStream;
import com.unionpay.sdk.AcpService;
import com.unionpay.sdk.LogUtil;
import com.unionpay.sdk.SDKConstants;
import com.weixin.api.WxMpInMemoryConfigStorage;
import com.weixin.api.WxMpService;
import com.weixin.api.WxMpServiceImpl;
import com.weixin.bean.result.NotifyMpPayResult;
import com.weixin.common.util.xml.XStreamInitializer;
import com.weixin.util.WxConfig;

/**
 * 支付通知控制器
 *
 * @author xiangwl
 */
@Controller
@RequestMapping("/paynotify")
public class PayNotifyController extends BaseController {

    @Autowired
    private ITenpayService tenpayService;
    @Autowired
    private IAlipayService alipayService;
    @Autowired
    private IRechargeOrderService rechargeOrderService;
    @Autowired
    private IServiceTripService serviceTripService;


    /**
     * 支付宝支付通知回调接口
     *
     * @param request
     * @param response
     * @throws UnsupportedEncodingException
     */
    @RequestMapping(value = "/alipay", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public void alipay(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        //获取支付宝POST过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter
                .hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            // 乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
            // valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
            params.put(name, valueStr);
        }
        logger.error("paynotify:alipay:requestParams=" + requestParams.toString());

        boolean flag = false;
        // 获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)//
        // 商户订单号 String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");

        // 支付宝交易号 String trade_no = new
        // String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");

        // 交易状态
        String trade_status = new String(params.get("trade_status").getBytes("ISO-8859-1"), "UTF-8");
        boolean pflag = false;
        //验证签名
        try {
            pflag = AlipaySignature.rsaCheckV1(params, AlipayConfig.ali_public_key, AlipayConfig.input_charset, "RSA2");
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        if (pflag) {// 验证成功
            /*// 获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以上仅供参考)//
            logger.error("paynotify:alipay:verify:start");
			if (AlipayNotify.verify(params)) {// 验证成功*/
            // ////////////////////////////////////////////////////////////////////////////////////////
            logger.error("paynotify:alipay:verify:success");
            // 请在这里加上商户的业务逻辑程序代码
            // ——请根据您的业务逻辑来编写程序（以下代码仅作参考）——
            //解析参数
            String buyerId = getMapValue(params, "buyer_id");
            String body = getMapValue(params, "body");
            String tradeNo = getMapValue(params, "trade_no");
            String useCoupon = getMapValue(params, "use_coupon");
            String notifyTime = getMapValue(params, "notify_time");
            String subject = getMapValue(params, "subject");
            String signType = getMapValue(params, "sign_type");
            String s_total_fee_adjust = getMapValue(params, "s_total_fee_adjust");
            String notifyType = getMapValue(params, "notify_type");
            String outTradeNo = getMapValue(params, "out_trade_no");
            String tradeStatus = getMapValue(params, "trade_status");
            String sign = getMapValue(params, "sign");
            String gmtCreate = getMapValue(params, "gmt_create");
            String sellerId = getMapValue(params, "seller_id");
            String buyerEmail = getMapValue(params, "buyer_email");
            String discount = getMapValue(params, "discount");
            String sellerEmail = getMapValue(params, "seller_email");
            double price = ConvertUtil.parseDouble(params.get("receipt_amount"));//新版实收价格回调参数已变// ConvertUtil.parseDouble(params.get("price"));
            double totalFee = ConvertUtil.parseDouble(params.get("total_amount"));//新版订单金额回调参数已变// ConvertUtil.parseDouble(params.get("total_fee"));
            long paymentType = ConvertUtil.parseLong(params.get("payment_type"));//此参数在新版中取消

            //支付宝记录实体
            Alipay alipay = new Alipay();
            alipay.setOutTradeNo(outTradeNo);
            alipay.setBuyerId(buyerId);
            alipay.setBody(body);
            alipay.setTradeNo(tradeNo);
            alipay.setUseCoupon(useCoupon);
            alipay.setNotifyTime(notifyTime);
            alipay.setSubject(subject);
            alipay.setSignType(signType);
            alipay.setSTotalFeeAdjust(s_total_fee_adjust);
            alipay.setNotifyType(notifyType);
            alipay.setTradeStatus(tradeStatus);
            alipay.setSign(sign);
            alipay.setGmtCreate(gmtCreate);
            alipay.setSellerId(sellerId);
            alipay.setBuyerEmail(buyerEmail);
            alipay.setDiscount(discount);
            alipay.setPrice(price);
            alipay.setTotalFee(totalFee);
            alipay.setPaymentType(paymentType);
            alipay.setSellerEmail(sellerEmail);
            logger.error("paynotify:alipay:verify:trade_status=" + trade_status);
            if (trade_status.equals("TRADE_FINISHED")) {
                // 判断该笔订单是否在商户网站中已经做过处理
                // 如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                // 如果有做过处理，不执行商户的业务程序

                // 注意：
                // 退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
                // 请务必判断请求时的total_fee、seller_id与通知时获取的total_fee、seller_id为一致的
            } else if (trade_status.equals("TRADE_SUCCESS")) {
                // 判断该笔订单是否在商户网站中已经做过处理
                // 如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                // 如果有做过处理，不执行商户的业务程序
                try {
                    //业务判断
                    //outTradeNo前面两位字符表示业务类型，参见OrderNoType枚举
                    String orderNoType = outTradeNo.substring(0, 2);
                    System.out.println("orderNoType=" + orderNoType);
                    //充值订单
                    if (TripNoType.CZ.getPrefix().equals(orderNoType)) {
                        flag = rechargeOrderService.payOrder("", outTradeNo, tradeNo, null, alipay);
                    } else {
                        //设置订单为支付成功
                        //如果在司机行程订单列表，那么要修改行程订单的支付状态为支付。
                        flag = serviceTripService.payTrip("", outTradeNo, tradeNo, null, alipay, null);
                    }
                } catch (Exception e) {
                    logger.error(e.getMessage());
                }
                // 注意：
                // 付款完成后，支付宝系统发送该交易状态通知
                // 请务必判断请求时的total_fee、seller_id与通知时获取的total_fee、seller_id为一致的
            }
            logger.error("paynotify:alipay:flag=" + flag);
            // ——请根据您的业务逻辑来编写程序（以上代码仅作参考）——

            try {
                if (flag) {
                    response.getWriter().write("success");
                } else {
                    response.getWriter().write("fail");
                }
            } catch (IOException e) {
                e.printStackTrace();
            } // 请不要修改或删除

            // ////////////////////////////////////////////////////////////////////////////////////////
        } else {// 验证失败
            try {
                logger.error("paynotify:alipay:verify:fail");
                response.getWriter().write("fail");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @RequestMapping(value = "/tenpay", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public void tenpay(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");

        BufferedReader reader = request.getReader();

        String buffer = null;
        StringBuffer stringBuffer = new StringBuffer();

        while ((buffer = reader.readLine()) != null) {
            stringBuffer.append(buffer);
        }
        String xmlString = stringBuffer.toString();
        logger.error("paynotify:tenpay::xmlString=" + xmlString);
        try {
            XStream xstream = XStreamInitializer.getInstance();
            xstream.alias("xml", NotifyMpPayResult.class);
            NotifyMpPayResult notifyMpPayResult = (NotifyMpPayResult) xstream.fromXML(xmlString);
            logger.error("return_code:" + notifyMpPayResult.getReturn_code() + ":result_code" + notifyMpPayResult.getResult_code());
            //return_code=SUCCESS and result_code=SUCCESS
            if ("SUCCESS".equalsIgnoreCase(notifyMpPayResult.getReturn_code()) &&
                    "SUCCESS".equalsIgnoreCase(notifyMpPayResult.getResult_code())) {

                WxMpInMemoryConfigStorage config = new WxMpInMemoryConfigStorage();
                config.setAppId(WxConfig.AppId);
                config.setSecret(WxConfig.AppSecret);
                config.setPartnerId(WxConfig.MchId);
                config.setPartnerKey(WxConfig.SignKey);
                WxMpService wxService = new WxMpServiceImpl();
                wxService.setWxMpConfigStorage(config);

                notifyMpPayResult = wxService.queryOrder(notifyMpPayResult.getOut_trade_no(), "");
                //获取任务订单编号
                String outTradeNo = notifyMpPayResult.getOut_trade_no();
                String transactionId = notifyMpPayResult.getTransaction_id();

                Tenpay tenpay = new Tenpay();
                tenpay.setTradeState(notifyMpPayResult.getTrade_state());
                tenpay.setBankType(notifyMpPayResult.getBank_type());
                tenpay.setTransactionId(transactionId);
                tenpay.setDeviceInfo(notifyMpPayResult.getDevice_info());
                tenpay.setIsSubscribe(notifyMpPayResult.getIs_subscribe());
                tenpay.setAttach(notifyMpPayResult.getAttach());
                tenpay.setTimeEnd(notifyMpPayResult.getTime_end());
                tenpay.setFeeType(notifyMpPayResult.getFee_type() + "");
                tenpay.setCashFee(notifyMpPayResult.getCash_fee() + "");
                tenpay.setTradeType(notifyMpPayResult.getTrade_type());
                tenpay.setPayReturnCode(notifyMpPayResult.getReturn_code());
                tenpay.setPayReturnMsg(notifyMpPayResult.getReturn_msg());
                tenpay.setPayResultCode(notifyMpPayResult.getResult_code());

                Boolean succeed = false;
                try {
                    String orderNoType = outTradeNo.substring(0, 2);
                    System.out.println("orderNoType=" + orderNoType);
                    //充值订单
                    if (TripNoType.CZ.getPrefix().equals(orderNoType)) {
                        succeed = rechargeOrderService.payOrder("", outTradeNo, transactionId, tenpay, null);
                    } else {
                        //设置订单为支付成功
                        //如果在司机行程订单列表，那么要修改行程订单的支付状态为支付。
                        System.out.println("支付成功，改变订单状态，订单号为" + outTradeNo+",transactionId="+transactionId);
                        succeed = serviceTripService.payTrip("", outTradeNo, transactionId, tenpay, null, null);
                    }
                } catch (Exception e) {
                    logger.error("异常："+e.getMessage());
                }
                if (succeed) {
                    response.getWriter().write("<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>");
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        response.getWriter().write("<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[修改订单状态失败]]></return_msg></xml>");
    }

    /**
     * 银联通知接口  post
     *
     * @param request
     * @param response
     * @throws UnsupportedEncodingException
     */
    @RequestMapping(value = "/unionpay", method = RequestMethod.POST, produces = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
    public void unionpay(HttpServletRequest request, HttpServletResponse response) throws IOException {
        logger.error("idinfo:params=收到消息1111111");
        //获取NockLOCK POST过来信息
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");

        LogUtil.writeLog("BackRcvResponse接收后台通知开始");
        String encoding = request.getParameter(SDKConstants.param_encoding);
        // 获取银联通知服务器发送的后台通知参数
        Map<String, String> reqParam = getAllRequestParam(request);
        LogUtil.printRequestLog(reqParam);

        //重要！验证签名前不要修改reqParam中的键值对的内容，否则会验签不过
        if (!AcpService.validate(reqParam, encoding)) {
            LogUtil.writeLog("验证签名结果[失败].");
            //验签失败，需解决验签问题
            logger.error("idinfo:params=验证签名结果[失败].");
        } else {
            logger.error("idinfo:params=验证签名结果[成功].");
            LogUtil.writeLog("验证签名结果[成功].");
            //【注：为了安全验签成功才应该写商户的成功处理逻辑】交易成功，更新商户订单状态
            String orderId = reqParam.get("orderId"); //获取后台通知的数据，其他字段也可用类似方式获取
            String respCode = reqParam.get("respCode");
            //判断respCode=00、A6后，对涉及资金类的交易，请再发起查询接口查询，确定交易成功后更新数据库。
            logger.error("idinfo:orderId" + orderId);
            String queryId = reqParam.get("queryId");
            String currencyCode = reqParam.get("currencyCode");
            String traceTime = reqParam.get("traceTime");
            String accNo = reqParam.get("accNo");
            String payType = reqParam.get("payType");
            String payCardNo = reqParam.get("payCardNo");
            String payCardType = reqParam.get("payCardType");
            String payCardIssueName = reqParam.get("payCardIssueName");
            String version = reqParam.get("version");
            String bindId = reqParam.get("bindId");
            String txnTime = reqParam.get("txnTime");
            String txnAmt = reqParam.get("txnAmt");
            String txnType = reqParam.get("txnType");
            String txnSubType = reqParam.get("txnSubType");
            String accessType = reqParam.get("accessType");
            String merId = reqParam.get("merId");


            Unionpay unionpay = new Unionpay();
            unionpay.setOrderId(orderId);
            unionpay.setQueryId(queryId);
            unionpay.setCurrencyCode(currencyCode);
            unionpay.setTraceTime(traceTime);
            unionpay.setAccNo(accNo);
            unionpay.setPayType(payType);
            unionpay.setPayCardno(payCardNo);
            unionpay.setPayCardtype(payCardType);
            unionpay.setPayCardIssueName(payCardIssueName);
            unionpay.setVersion(version);
            unionpay.setBindId(bindId);
            unionpay.setTxnTime(txnTime);
            unionpay.setTxnAmt(txnAmt);
            unionpay.setTxnType(txnType);
            unionpay.setMerId(merId);

            Boolean succeed = false;
            try {
                /*String orderNoType = outTradeNo.substring(0, 2);
                System.out.println("orderNoType=" + orderNoType);
                //充值订单
                if (TripNoType.CZ.getPrefix().equals(orderNoType)) {
                    //succeed = rechargeOrderService.payOrder("", outTradeNo, transactionId, tenpay, null);
                } else {
                    //设置订单为支付成功
                    succeed = serviceTripService.payTrip("", "", "", null, null,unionpay);
                }*/
                succeed = serviceTripService.payTrip("", orderId, queryId, null, null, unionpay);

            } catch (Exception e) {
                logger.error(e.getMessage());
            }
            if (succeed) {
                LogUtil.writeLog("BackRcvResponse接收后台通知结束");
                //返回给银联服务器http 200  状态码
                response.getWriter().print("ok");
            }
        }
    }

    private String getMapValue(Map<String, String> map, String key) {
        if (map == null)
            return "";
        if (map.containsKey(key))
            return map.get(key);
        return "";
    }

    /**
     * 获取请求参数中所有的信息
     *
     * @param request
     * @return
     */
    public static Map<String, String> getAllRequestParam(final HttpServletRequest request) {
        Map<String, String> res = new HashMap<String, String>();
        Enumeration<?> temp = request.getParameterNames();
        if (null != temp) {
            while (temp.hasMoreElements()) {
                String en = (String) temp.nextElement();
                String value = request.getParameter(en);
                res.put(en, value);
                //在报文上送时，如果字段的值为空，则不上送<下面的处理为在获取所有参数数据时，判断若值为空，则删除这个字段>
                //System.out.println("ServletUtil类247行  temp数据的键=="+en+"     值==="+value);
                if (null == res.get(en) || "".equals(res.get(en))) {
                    res.remove(en);
                }
            }
        }
        return res;
    }

}
